package com.work.yshop.mvp.model;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.Product;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.provider.ProductProvider;
import com.work.yshop.provider.UserDataProvider;
import com.work.yshop.utils.UserSession;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 用户数据模型
 * 实现Model层，用于操作UserDataProvider
 */
public class UserDataModel {
    private static final String TAG = "UserDataModel";
    
    private Context context;
    private ContentResolver contentResolver;
    
    public UserDataModel(Context context) {
        this.context = context.getApplicationContext();
        this.contentResolver = context.getContentResolver();
    }
    
    /**
     * 添加商品浏览记录
     */
    public boolean addHistory(Product product) {
        if (product == null) return false;
        
        try {
            // 先删除已有的相同商品记录
            contentResolver.delete(
                    UserDataProvider.HISTORY_URI,
                    "product_id = ? AND user_id = ?",
                    new String[]{String.valueOf(product.getId()), String.valueOf(UserSession.getInstance().getUserId())}
            );
            
            // 添加新记录
            ContentValues values = new ContentValues();
            values.put("product_id", product.getId());
            values.put("user_id", UserSession.getInstance().getUserId());
            values.put("view_time", System.currentTimeMillis());
            
            Uri uri = contentResolver.insert(UserDataProvider.HISTORY_URI, values);
            return uri != null;
        } catch (Exception e) {
            Log.e(TAG, "添加浏览记录失败", e);
            return false;
        }
    }
    
    /**
     * 获取商品浏览记录列表
     */
    public List<ProductHistory> getHistoryList() {
        List<ProductHistory> historyList = new ArrayList<>();
        
        try {
            Cursor cursor = contentResolver.query(
                    UserDataProvider.HISTORY_URI,
                    null,
                    "user_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())},
                    "view_time DESC"
            );
            
            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        int productId = cursor.getInt(cursor.getColumnIndexOrThrow("product_id"));
                        int userId = cursor.getInt(cursor.getColumnIndexOrThrow("user_id"));
                        long viewTime = cursor.getLong(cursor.getColumnIndexOrThrow("view_time"));
                        
                        ProductHistory history = new ProductHistory(productId, userId, viewTime);
                        history.setId(id);
                        
                        // 获取商品信息
                        Product product = getProductById(productId);
                        history.setProduct(product);
                        
                        historyList.add(history);
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取浏览记录失败", e);
        }
        
        return historyList;
    }
    
    /**
     * 清空浏览记录
     */
    public boolean clearHistory() {
        try {
            int count = contentResolver.delete(
                    UserDataProvider.HISTORY_URI,
                    "user_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())}
            );
            return count > 0;
        } catch (Exception e) {
            Log.e(TAG, "清空浏览记录失败", e);
            return false;
        }
    }
    
    /**
     * 添加收藏
     */
    public boolean addFavorite(Product product) {
        if (product == null) return false;
        
        try {
            // 检查是否已收藏
            if (isFavorite(product.getId())) {
                return true;
            }
            
            // 添加新收藏
            ContentValues values = new ContentValues();
            values.put("product_id", product.getId());
            values.put("user_id", UserSession.getInstance().getUserId());
            values.put("favorite_time", System.currentTimeMillis());
            
            Uri uri = contentResolver.insert(UserDataProvider.FAVORITES_URI, values);
            return uri != null;
        } catch (Exception e) {
            Log.e(TAG, "添加收藏失败", e);
            return false;
        }
    }
    
    /**
     * 取消收藏
     */
    public boolean removeFavorite(int productId) {
        try {
            int count = contentResolver.delete(
                    UserDataProvider.FAVORITES_URI,
                    "product_id = ? AND user_id = ?",
                    new String[]{String.valueOf(productId), String.valueOf(UserSession.getInstance().getUserId())}
            );
            return count > 0;
        } catch (Exception e) {
            Log.e(TAG, "取消收藏失败", e);
            return false;
        }
    }
    
    /**
     * 是否已收藏
     */
    public boolean isFavorite(int productId) {
        try {
            Cursor cursor = contentResolver.query(
                    UserDataProvider.FAVORITES_URI,
                    new String[]{"_id"},
                    "product_id = ? AND user_id = ?",
                    new String[]{String.valueOf(productId), String.valueOf(UserSession.getInstance().getUserId())},
                    null
            );
            
            if (cursor != null) {
                try {
                    return cursor.getCount() > 0;
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "检查收藏状态失败", e);
        }
        
        return false;
    }
    
    /**
     * 获取收藏列表
     */
    public List<Favorite> getFavoriteList() {
        List<Favorite> favoriteList = new ArrayList<>();
        
        try {
            Cursor cursor = contentResolver.query(
                    UserDataProvider.FAVORITES_URI,
                    null,
                    "user_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())},
                    "favorite_time DESC"
            );
            
            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        int productId = cursor.getInt(cursor.getColumnIndexOrThrow("product_id"));
                        int userId = cursor.getInt(cursor.getColumnIndexOrThrow("user_id"));
                        long favoriteTime = cursor.getLong(cursor.getColumnIndexOrThrow("favorite_time"));
                        
                        Favorite favorite = new Favorite(productId, userId, favoriteTime);
                        favorite.setId(id);
                        
                        // 获取商品信息
                        Product product = getProductById(productId);
                        favorite.setProduct(product);
                        
                        favoriteList.add(favorite);
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取收藏列表失败", e);
        }
        
        return favoriteList;
    }
    
    /**
     * 添加商品到购物车
     */
    public boolean addToCart(Product product, int quantity) {
        if (product == null || quantity <= 0) return false;
        
        try {
            // 检查购物车是否已有该商品
            Cursor cursor = contentResolver.query(
                    UserDataProvider.CART_URI,
                    new String[]{"_id", "quantity"},
                    "product_id = ? AND user_id = ?",
                    new String[]{String.valueOf(product.getId()), String.valueOf(UserSession.getInstance().getUserId())},
                    null
            );
            
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        // 已存在，更新数量
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        int currentQuantity = cursor.getInt(cursor.getColumnIndexOrThrow("quantity"));
                        
                        ContentValues values = new ContentValues();
                        values.put("quantity", currentQuantity + quantity);
                        
                        int count = contentResolver.update(
                                Uri.withAppendedPath(UserDataProvider.CART_URI, String.valueOf(id)),
                                values,
                                null,
                                null
                        );
                        
                        return count > 0;
                    }
                } finally {
                    cursor.close();
                }
            }
            
            // 添加新商品
            ContentValues values = new ContentValues();
            values.put("product_id", product.getId());
            values.put("user_id", UserSession.getInstance().getUserId());
            values.put("quantity", quantity);
            values.put("selected", 1); // 默认选中
            values.put("add_time", System.currentTimeMillis());
            
            Uri uri = contentResolver.insert(UserDataProvider.CART_URI, values);
            return uri != null;
        } catch (Exception e) {
            Log.e(TAG, "添加到购物车失败", e);
            return false;
        }
    }
    
    /**
     * 更新购物车商品数量
     */
    public boolean updateCartItemQuantity(int productId, int quantity) {
        if (quantity <= 0) {
            return removeCartItem(productId);
        }
        
        try {
            Cursor cursor = contentResolver.query(
                    UserDataProvider.CART_URI,
                    new String[]{"_id"},
                    "product_id = ? AND user_id = ?",
                    new String[]{String.valueOf(productId), String.valueOf(UserSession.getInstance().getUserId())},
                    null
            );
            
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        
                        ContentValues values = new ContentValues();
                        values.put("quantity", quantity);
                        
                        int count = contentResolver.update(
                                Uri.withAppendedPath(UserDataProvider.CART_URI, String.valueOf(id)),
                                values,
                                null,
                                null
                        );
                        
                        return count > 0;
                    }
                } finally {
                    cursor.close();
                }
            }
            
            return false;
        } catch (Exception e) {
            Log.e(TAG, "更新购物车商品数量失败", e);
            return false;
        }
    }
    
    /**
     * 从购物车移除商品
     */
    public boolean removeCartItem(int productId) {
        try {
            int count = contentResolver.delete(
                    UserDataProvider.CART_URI,
                    "product_id = ? AND user_id = ?",
                    new String[]{String.valueOf(productId), String.valueOf(UserSession.getInstance().getUserId())}
            );
            return count > 0;
        } catch (Exception e) {
            Log.e(TAG, "从购物车移除商品失败", e);
            return false;
        }
    }
    
    /**
     * 获取购物车商品列表
     */
    public List<CartItem> getCartItems() {
        List<CartItem> cartItems = new ArrayList<>();
        
        try {
            Cursor cursor = contentResolver.query(
                    UserDataProvider.CART_URI,
                    null,
                    "user_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())},
                    "add_time DESC"
            );
            
            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                        int productId = cursor.getInt(cursor.getColumnIndexOrThrow("product_id"));
                        int userId = cursor.getInt(cursor.getColumnIndexOrThrow("user_id"));
                        int quantity = cursor.getInt(cursor.getColumnIndexOrThrow("quantity"));
                        boolean selected = cursor.getInt(cursor.getColumnIndexOrThrow("selected")) == 1;
                        long addTime = cursor.getLong(cursor.getColumnIndexOrThrow("add_time"));
                        
                        CartItem cartItem = new CartItem(productId, userId, quantity);
                        cartItem.setId(id);
                        cartItem.setSelected(selected);
                        cartItem.setAddTime(addTime);
                        
                        // 获取商品信息
                        Product product = getProductById(productId);
                        cartItem.setProduct(product);
                        
                        cartItems.add(cartItem);
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取购物车商品列表失败", e);
        }
        
        return cartItems;
    }
    
    /**
     * 清空购物车
     */
    public boolean clearCart() {
        try {
            int count = contentResolver.delete(
                    UserDataProvider.CART_URI,
                    "user_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())}
            );
            return count > 0;
        } catch (Exception e) {
            Log.e(TAG, "清空购物车失败", e);
            return false;
        }
    }
    
    /**
     * 创建订单
     */
    public Order createOrder() {
        // 获取选中的购物车项
        List<CartItem> selectedItems = new ArrayList<>();
        List<CartItem> allItems = getCartItems();
        
        for (CartItem item : allItems) {
            if (item.isSelected() && item.getProduct() != null) {
                selectedItems.add(item);
            }
        }
        
        if (selectedItems.isEmpty()) {
            return null;
        }
        
        return createOrderFromItems(selectedItems);
    }
    
    /**
     * 创建只包含指定选中商品的订单
     */
    public Order createSelectedOrder(List<CartItem> selectedItems) {
        if (selectedItems == null || selectedItems.isEmpty()) {
            return null;
        }
        
        // 确保所有项都有产品信息
        List<CartItem> validItems = new ArrayList<>();
        for (CartItem item : selectedItems) {
            if (item.isSelected() && item.getProduct() != null) {
                validItems.add(item);
            }
        }
        
        if (validItems.isEmpty()) {
            return null;
        }
        
        return createOrderFromItems(validItems);
    }
    
    /**
     * 从购物车项创建订单的公共方法
     */
    private Order createOrderFromItems(List<CartItem> items) {
        try {
            // 创建订单
            ContentValues orderValues = new ContentValues();
            
            // 生成订单编号
            String orderNumber = "O" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()) +
                    String.format("%04d", UserSession.getInstance().getUserId());
            orderValues.put("order_number", orderNumber);
            
            // 设置订单信息
            orderValues.put("user_id", UserSession.getInstance().getUserId());
            orderValues.put("buyer_name", UserSession.getInstance().getUsername());
            orderValues.put("order_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
            orderValues.put("status", Order.STATUS_PROCESSING);
            
            // 计算总金额
            double totalAmount = 0;
            for (CartItem item : items) {
                totalAmount += item.getSubtotal();
            }
            orderValues.put("total_amount", totalAmount);
            
            // 插入订单
            Uri orderUri = contentResolver.insert(UserDataProvider.ORDERS_URI, orderValues);
            if (orderUri == null) {
                return null;
            }
            
            // 获取订单ID
            long orderId = Long.parseLong(orderUri.getLastPathSegment());
            
            // 添加订单项
            for (CartItem item : items) {
                ContentValues itemValues = new ContentValues();
                itemValues.put("order_id", orderId);
                itemValues.put("product_id", item.getProductId());
                itemValues.put("product_name", item.getProduct().getName());
                itemValues.put("price", item.getProduct().getPrice());
                itemValues.put("quantity", item.getQuantity());
                itemValues.put("image_url", item.getProduct().getImageUrl());
                
                contentResolver.insert(UserDataProvider.ORDER_ITEMS_URI, itemValues);
            }
            
            // 从购物车中移除已下单的商品
            for (CartItem item : items) {
                removeCartItem(item.getProductId());
            }
            
            // 返回创建的订单
            return getOrderById(orderId);
        } catch (Exception e) {
            Log.e(TAG, "创建订单失败", e);
            return null;
        }
    }
    
    /**
     * 获取订单列表
     */
    public List<Order> getOrderList() {
        List<Order> orderList = new ArrayList<>();
        
        try {
            Cursor cursor = contentResolver.query(
                    UserDataProvider.ORDERS_URI,
                    null,
                    "user_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())},
                    "order_time DESC"
            );
            
            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
                        String orderNumber = cursor.getString(cursor.getColumnIndexOrThrow("order_number"));
                        String buyerName = cursor.getString(cursor.getColumnIndexOrThrow("buyer_name"));
                        String orderTime = cursor.getString(cursor.getColumnIndexOrThrow("order_time"));
                        double totalAmount = cursor.getDouble(cursor.getColumnIndexOrThrow("total_amount"));
                        int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));
                        
                        Order order = new Order(orderNumber, buyerName, orderTime, totalAmount, status);
                        
                        // 获取订单项
                        Cursor itemsCursor = contentResolver.query(
                                UserDataProvider.ORDER_ITEMS_URI,
                                null,
                                "order_id = ?",
                                new String[]{String.valueOf(id)},
                                null
                        );
                        
                        if (itemsCursor != null) {
                            try {
                                while (itemsCursor.moveToNext()) {
                                    int productId = itemsCursor.getInt(itemsCursor.getColumnIndexOrThrow("product_id"));
                                    String productName = itemsCursor.getString(itemsCursor.getColumnIndexOrThrow("product_name"));
                                    double price = itemsCursor.getDouble(itemsCursor.getColumnIndexOrThrow("price"));
                                    int quantity = itemsCursor.getInt(itemsCursor.getColumnIndexOrThrow("quantity"));
                                    String imageUrl = itemsCursor.getString(itemsCursor.getColumnIndexOrThrow("image_url"));
                                    
                                    Order.OrderItem orderItem = new Order.OrderItem(
                                            productId, productName, price, quantity, imageUrl
                                    );
                                    order.addItem(orderItem);
                                }
                            } finally {
                                itemsCursor.close();
                            }
                        }
                        
                        orderList.add(order);
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取订单列表失败", e);
        }
        
        // 如果订单列表为空，创建一些模拟订单
        if (orderList.isEmpty()) {
            createMockOrders().forEach(order -> {
                Order savedOrder = saveDirectOrder(order);
                if (savedOrder != null) {
                    orderList.add(savedOrder);
                }
            });
        }
        
        return orderList;
    }
    
    /**
     * 创建模拟订单
     */
    private List<Order> createMockOrders() {
        List<Order> mockOrders = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        
        // 模拟订单1：待付款
        Order order1 = new Order();
        order1.setOrderNumber("O" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(calendar.getTime()) + 
                String.format("%04d", UserSession.getInstance().getUserId()) + "1");
        order1.setBuyerName(UserSession.getInstance().getUsername());
        order1.setOrderTime(dateFormat.format(calendar.getTime()));
        order1.setStatus(Order.STATUS_PENDING);
        
        // 添加订单项
        Order.OrderItem item1 = new Order.OrderItem(
                1,
                "有机胡萝卜 新鲜蔬菜",
                5.99,
                2,
                "https://images.pexels.com/photos/143133/pexels-photo-143133.jpeg"
        );
        order1.addItem(item1);
        order1.setTotalAmount(item1.getSubtotal());
        mockOrders.add(order1);
        
        // 模拟订单2：待发货
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        Order order2 = new Order();
        order2.setOrderNumber("O" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(calendar.getTime()) + 
                String.format("%04d", UserSession.getInstance().getUserId()) + "2");
        order2.setBuyerName(UserSession.getInstance().getUsername());
        order2.setOrderTime(dateFormat.format(calendar.getTime()));
        order2.setStatus(Order.STATUS_PROCESSING);
        
        // 添加订单项
        Order.OrderItem item2_1 = new Order.OrderItem(
                2,
                "新鲜西红柿 自然成熟",
                3.99,
                3,
                "https://images.pexels.com/photos/533280/pexels-photo-533280.jpeg"
        );
        Order.OrderItem item2_2 = new Order.OrderItem(
                3,
                "有机黄瓜 农家种植",
                2.49,
                5,
                "https://images.pexels.com/photos/2329440/pexels-photo-2329440.jpeg"
        );
        order2.addItem(item2_1);
        order2.addItem(item2_2);
        order2.setTotalAmount(item2_1.getSubtotal() + item2_2.getSubtotal());
        mockOrders.add(order2);
        
        // 模拟订单3：已发货
        calendar.add(Calendar.DAY_OF_MONTH, -3);
        Order order3 = new Order();
        order3.setOrderNumber("O" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(calendar.getTime()) + 
                String.format("%04d", UserSession.getInstance().getUserId()) + "3");
        order3.setBuyerName(UserSession.getInstance().getUsername());
        order3.setOrderTime(dateFormat.format(calendar.getTime()));
        order3.setStatus(Order.STATUS_SHIPPED);
        
        // 添加订单项
        Order.OrderItem item3 = new Order.OrderItem(
                4,
                "云南新鲜水果山竹",
                19.90,
                1,
                "https://images.pexels.com/photos/1435904/pexels-photo-1435904.jpeg"
        );
        order3.addItem(item3);
        order3.setTotalAmount(item3.getSubtotal());
        mockOrders.add(order3);
        
        // 模拟订单4：已完成
        calendar.add(Calendar.DAY_OF_MONTH, -10);
        Order order4 = new Order();
        order4.setOrderNumber("O" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(calendar.getTime()) + 
                String.format("%04d", UserSession.getInstance().getUserId()) + "4");
        order4.setBuyerName(UserSession.getInstance().getUsername());
        order4.setOrderTime(dateFormat.format(calendar.getTime()));
        order4.setStatus(Order.STATUS_COMPLETED);
        
        // 添加订单项
        Order.OrderItem item4_1 = new Order.OrderItem(
                5,
                "有机鸡蛋 散养土鸡蛋",
                23.80,
                2,
                "https://images.pexels.com/photos/162712/egg-white-food-protein-162712.jpeg"
        );
        order4.addItem(item4_1);
        order4.setTotalAmount(item4_1.getSubtotal());
        mockOrders.add(order4);
        
        return mockOrders;
    }
    
    /**
     * 根据ID获取订单
     */
    private Order getOrderById(long orderId) {
        try {
            Cursor cursor = contentResolver.query(
                    Uri.withAppendedPath(UserDataProvider.ORDERS_URI, String.valueOf(orderId)),
                    null,
                    null,
                    null,
                    null
            );
            
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        String orderNumber = cursor.getString(cursor.getColumnIndexOrThrow("order_number"));
                        String buyerName = cursor.getString(cursor.getColumnIndexOrThrow("buyer_name"));
                        String orderTime = cursor.getString(cursor.getColumnIndexOrThrow("order_time"));
                        double totalAmount = cursor.getDouble(cursor.getColumnIndexOrThrow("total_amount"));
                        int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));
                        
                        Order order = new Order(orderNumber, buyerName, orderTime, totalAmount, status);
                        
                        // 获取订单项
                        Cursor itemsCursor = contentResolver.query(
                                UserDataProvider.ORDER_ITEMS_URI,
                                null,
                                "order_id = ?",
                                new String[]{String.valueOf(orderId)},
                                null
                        );
                        
                        if (itemsCursor != null) {
                            try {
                                while (itemsCursor.moveToNext()) {
                                    int productId = itemsCursor.getInt(itemsCursor.getColumnIndexOrThrow("product_id"));
                                    String productName = itemsCursor.getString(itemsCursor.getColumnIndexOrThrow("product_name"));
                                    double price = itemsCursor.getDouble(itemsCursor.getColumnIndexOrThrow("price"));
                                    int quantity = itemsCursor.getInt(itemsCursor.getColumnIndexOrThrow("quantity"));
                                    String imageUrl = itemsCursor.getString(itemsCursor.getColumnIndexOrThrow("image_url"));
                                    
                                    Order.OrderItem orderItem = new Order.OrderItem(
                                            productId, productName, price, quantity, imageUrl
                                    );
                                    order.addItem(orderItem);
                                }
                            } finally {
                                itemsCursor.close();
                            }
                        }
                        
                        return order;
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取订单失败", e);
        }
        
        return null;
    }
    
    /**
     * 直接保存订单（立即购买）
     */
    public Order saveDirectOrder(Order order) {
        try {
            // 创建订单
            ContentValues orderValues = new ContentValues();
            
            // 订单信息
            orderValues.put("order_number", order.getOrderNumber());
            orderValues.put("user_id", UserSession.getInstance().getUserId());
            orderValues.put("buyer_name", order.getBuyerName());
            orderValues.put("order_time", order.getOrderTime());
            orderValues.put("status", order.getStatus());
            orderValues.put("total_amount", order.getTotalAmount());
            
            // 插入订单
            Uri orderUri = contentResolver.insert(UserDataProvider.ORDERS_URI, orderValues);
            if (orderUri == null) {
                return null;
            }
            
            // 获取订单ID
            long orderId = Long.parseLong(orderUri.getLastPathSegment());
            
            // 添加订单项
            for (Order.OrderItem item : order.getItems()) {
                ContentValues itemValues = new ContentValues();
                itemValues.put("order_id", orderId);
                itemValues.put("product_id", item.getProductId());
                itemValues.put("product_name", item.getProductName());
                itemValues.put("price", item.getPrice());
                itemValues.put("quantity", item.getQuantity());
                itemValues.put("image_url", item.getImageUrl());
                
                contentResolver.insert(UserDataProvider.ORDER_ITEMS_URI, itemValues);
            }
            
            // 返回创建的订单
            return getOrderById(orderId);
        } catch (Exception e) {
            Log.e(TAG, "直接创建订单失败", e);
            return null;
        }
    }
    
    /**
     * 根据ID获取商品
     */
    private Product getProductById(int productId) {
        Log.d(TAG, "getProductById: 开始获取商品, productId=" + productId);
        
        try {
            Uri uri = Uri.withAppendedPath(ProductProvider.CONTENT_URI, String.valueOf(productId));
            Log.d(TAG, "getProductById: 查询URI=" + uri);
            
            Cursor cursor = contentResolver.query(
                    uri,
                    null,
                    null,
                    null,
                    null
            );
            
            if (cursor != null) {
                try {
                    Log.d(TAG, "getProductById: 查询结果数量=" + cursor.getCount());
                    
                    if (cursor.moveToFirst()) {
                        String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
                        String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
                        double price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
                        double originalPrice = cursor.getDouble(cursor.getColumnIndexOrThrow("original_price"));
                        String unit = cursor.getString(cursor.getColumnIndexOrThrow("unit"));
                        int salesCount = cursor.getInt(cursor.getColumnIndexOrThrow("sales_count"));
                        String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
                        
                        Product product = new Product(productId, name, description, price, originalPrice, unit, salesCount, imageUrl);
                        Log.d(TAG, "getProductById: 成功获取商品, name=" + name + ", price=" + price);
                        return product;
                    } else {
                        Log.w(TAG, "getProductById: 未找到商品, productId=" + productId);
                    }
                } finally {
                    cursor.close();
                }
            } else {
                Log.w(TAG, "getProductById: 查询结果为空");
            }
        } catch (Exception e) {
            Log.e(TAG, "getProductById: 获取商品失败", e);
        }
        
        // 如果获取失败，返回一个默认商品
        Log.w(TAG, "getProductById: 返回默认商品");
        return new Product(productId, "未知商品", "商品信息不可用", 0, 0, "件", 0, "");
    }
} 